package Server;

import Protobuf.ChatProto;
import Server.Cache.*;
import Server.Common.*;
import io.netty.channel.*;

/**
 * @author jedi
 */
public class ServerHandler extends SimpleChannelInboundHandler<ChatProto.Msg> {
    public static Scene scene =new Scene();
    private final MessageQueue messageQueue = new MessageQueue();

    @Override
    public void channelActive(ChannelHandlerContext ctx){
        Channel channel = ctx.channel();
        MsgSession session = new MsgSession(channel,ChannelState.ONLINE);
        if(!ChannelUtil.online(channel,session)){
            channel.close();
            return;
        }
        messageQueue.acceptMsg(session);
        System.out.println(channel.remoteAddress()+"已连接\n");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatProto.Msg msg){
        MsgSession session = ChannelUtil.getSession(ctx.channel());
        session.setMsg(msg);
        session.setChannelState(ChannelState.RUNNING);
        messageQueue.acceptMsg(session);
   }

    @Override
    public void channelInactive(ChannelHandlerContext ctx){
        MsgSession session = ChannelUtil.getSession(ctx.channel());
        session.setChannelState(ChannelState.OFFLINE);
        messageQueue.acceptMsg(session);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Channel channel = ctx.channel();
        if(channel.isActive()){
            ctx.close();
        }
    }


}
